/*



 */
package com.springx.shiro.filter;

import com.google.common.collect.Maps;
import com.springx.shiro.domain.Principal;
import com.springx.shiro.domain.ShiroResource;
import com.springx.shiro.service.ShiroAccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Filter - 权限认证
 */

public class AuthenticationFilter extends FormAuthenticationFilter {
    private ShiroAccountService    shiroAccountService;
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.addHeader("loginStatus", "accessDenied");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        return super.onAccessDenied(request, response);
    }

    @Override
    protected boolean onLoginSuccess(org.apache.shiro.authc.AuthenticationToken token, Subject subject, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        Session session = subject.getSession();
        Map<Object, Object> attributes = new HashMap<Object, Object>();
        Collection<Object> keys = session.getAttributeKeys();
        for (Object key : keys) {
            attributes.put(key, session.getAttribute(key));
        }
        session.stop();
        session = subject.getSession();
        for (Entry<Object, Object> entry : attributes.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
        //存储加载菜单
        Map<Long, List<ShiroResource>> menus = Maps.newHashMap();
        Principal  principal =(Principal)  subject.getPrincipal();
        principal.setMenus(shiroAccountService.findMenuListByLoginName(principal.getUsername()));
        return super.onLoginSuccess(token, subject, servletRequest, servletResponse);
    }


    public void setShiroAccountService(ShiroAccountService shiroAccountService) {
        this.shiroAccountService = shiroAccountService;
    }
}